package net.trade.service.db;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.core.base.dao.CommonDAO;
import net.core.common.DateFormater;
import net.core.common.StrUtils;
import net.system.base.module.Column;
import net.system.base.module.Table;
import net.system.sys.service.ICommService;

@Service
public class CommonDB {
	
	@Autowired
	private CommonDAO commonDAO;

	@Autowired
	private ICommService commService;
	
	public void insertData(HashMap map, Table tTable) {
		String sql = "insert into <table>(<columns>)VALUES(<values>)";
		// 拼装值
		// 给对象赋值
		List<Column> columns = tTable.getList();
		columns = setColumnsValue(columns, map);
		tTable.setList(columns);
		// 拼接保存字段
		String sCol = getCol(columns);
		String sVal = getVal(columns);
		// 系统字段
		sql = sql.replace("<table>", tTable.getName()).replace("<columns>", sCol);
		sql = sql.replace("<values>", sVal);
		System.out.println(sql);
		commonDAO.insertSql(sql);
	}
	
	private String getVal(List<Column> columns) {
		String sReturn = "";
		if (null != columns && columns.size() > 0) {
			for (Column column : columns) {
				if (null != column.getValue() && !"".equals(column.getValue())) {
					// 加上类型判断
					sReturn += ",'" + column.getValue() + "'";
				}
			}
		}
		return sReturn.substring(1);
	}

	private String getCol(List<Column> columns) {
		String sReturn = "";
		if (null != columns && columns.size() > 0) {
			for (Column column : columns) {
				if (null != column.getValue() && !"".equals(column.getValue())) {
					sReturn += "," + column.getName();
				}
			}
		}
		return sReturn.substring(1);
	}

	private List<Column> setColumnsValue(List<Column> columns, Map reqMap) {

		if (null != columns && columns.size() > 0) {
			for (Column column : columns) {
				String sVal = "";
				if (column.isSys()) {
					if (column.getName().equals("REC_ID")) {
						sVal = commService.getSeq("trade");
					} else if (column.getName().equals("REC_PERSON")) {
						sVal = StrUtils.getNotNullStrValue(reqMap.get("user"));
						if ("".equals(sVal)) {
							sVal = "sysdef";
						}
					} else if (column.getName().equals("REC_TIME")) {
						sVal = DateFormater.getNowTime();
					}
				} else {
					sVal = StrUtils.getNotNullStrValue(reqMap.get(column.getAlias()));
					
				}
				column.setValue(sVal);
			}
		}
		return columns;
	}
}
